// 全局变量
let isRecording = false;
let isPlaying = false;
let events = [];
let startTime = 0;
let playbackInterval = null;

// DOM元素
const recordBtn = document.getElementById('recordBtn');
const playBtn = document.getElementById('playBtn');
const clearBtn = document.getElementById('clearBtn');
const speedSlider = document.getElementById('speedSlider');
const speedDisplay = document.getElementById('speedDisplay');
const recordStatus = document.getElementById('recordStatus');
const playStatus = document.getElementById('playStatus');
const eventCount = document.getElementById('eventCount');
const recordDuration = document.getElementById('recordDuration');
const eventList = document.getElementById('eventList');

// 事件监听器
recordBtn.addEventListener('click', toggleRecording);
playBtn.addEventListener('click', togglePlayback);
clearBtn.addEventListener('click', clearRecording);
speedSlider.addEventListener('input', updateSpeedDisplay);

// 键盘事件监听
document.addEventListener('keydown', handleKeyDown);
document.addEventListener('keyup', handleKeyUp);
document.addEventListener('mousemove', handleMouseMove);
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);

// 更新速度显示
function updateSpeedDisplay() {
    speedDisplay.textContent = speedSlider.value + 'x';
}

// 切换录制状态
function toggleRecording() {
    if (isRecording) {
        stopRecording();
    } else {
        startRecording();
    }
}

// 开始录制
function startRecording() {
    isRecording = true;
    events = [];
    startTime = Date.now();
    
    recordBtn.innerHTML = '<i class="fas fa-stop mr-2"></i>停止录制';
    recordBtn.classList.remove('btn-error');
    recordBtn.classList.add('btn-warning');
    recordStatus.textContent = '录制中...';
    recordStatus.classList.add('recording-indicator');
    
    playBtn.disabled = true;
    
    // 添加开始事件
    addEvent('start', { message: '开始录制' });
}

// 停止录制
function stopRecording() {
    isRecording = false;
    
    recordBtn.innerHTML = '<i class="fas fa-circle mr-2"></i>开始录制';
    recordBtn.classList.remove('btn-warning');
    recordBtn.classList.add('btn-error');
    recordStatus.textContent = '已停止';
    recordStatus.classList.remove('recording-indicator');
    
    if (events.length > 0) {
        playBtn.disabled = false;
    }
    
    // 添加结束事件
    addEvent('stop', { message: '停止录制' });
}

// 切换回放状态
function togglePlayback() {
    if (isPlaying) {
        stopPlayback();
    } else {
        startPlayback();
    }
}

// 开始回放
function startPlayback() {
    if (events.length === 0) return;
    
    isPlaying = true;
    const speed = parseFloat(speedSlider.value);
    
    playBtn.innerHTML = '<i class="fas fa-stop mr-2"></i>停止回放';
    playBtn.classList.remove('btn-success');
    playBtn.classList.add('btn-warning');
    playStatus.textContent = '回放中...';
    playStatus.classList.add('recording-indicator');
    
    recordBtn.disabled = true;
    
    // 执行回放
    executePlayback(events, speed);
}

// 停止回放
function stopPlayback() {
    isPlaying = false;
    
    if (playbackInterval) {
        clearInterval(playbackInterval);
        playbackInterval = null;
    }
    
    playBtn.innerHTML = '<i class="fas fa-play mr-2"></i>开始回放';
    playBtn.classList.remove('btn-warning');
    playBtn.classList.add('btn-success');
    playStatus.textContent = '已停止';
    playStatus.classList.remove('recording-indicator');
    
    recordBtn.disabled = false;
}

// 清空录制
function clearRecording() {
    events = [];
    updateEventList();
    updateStats();
    playBtn.disabled = true;
}

// 添加事件
function addEvent(type, data) {
    const event = {
        type: type,
        timestamp: Date.now() - startTime,
        data: data
    };
    
    events.push(event);
    updateEventList();
    updateStats();
}

// 处理键盘按下事件
function handleKeyDown(e) {
    if (!isRecording) return;
    
    addEvent('keydown', {
        key: e.key,
        code: e.code,
        ctrlKey: e.ctrlKey,
        shiftKey: e.shiftKey,
        altKey: e.altKey,
        metaKey: e.metaKey
    });
}

// 处理键盘释放事件
function handleKeyUp(e) {
    if (!isRecording) return;
    
    addEvent('keyup', {
        key: e.key,
        code: e.code,
        ctrlKey: e.ctrlKey,
        shiftKey: e.shiftKey,
        altKey: e.altKey,
        metaKey: e.metaKey
    });
}

// 处理鼠标移动事件
function handleMouseMove(e) {
    if (!isRecording) return;
    
    addEvent('mousemove', {
        x: e.clientX,
        y: e.clientY,
        screenX: e.screenX,
        screenY: e.screenY
    });
}

// 处理鼠标按下事件
function handleMouseDown(e) {
    if (!isRecording) return;
    
    addEvent('mousedown', {
        x: e.clientX,
        y: e.clientY,
        screenX: e.screenX,
        screenY: e.screenY,
        button: e.button,
        buttons: e.buttons
    });
}

// 处理鼠标释放事件
function handleMouseUp(e) {
    if (!isRecording) return;
    
    addEvent('mouseup', {
        x: e.clientX,
        y: e.clientY,
        screenX: e.screenX,
        screenY: e.screenY,
        button: e.button,
        buttons: e.buttons
    });
}

// 执行回放
function executePlayback(events, speed) {
    let index = 0;
    
    function executeNext() {
        if (index >= events.length || !isPlaying) {
            stopPlayback();
            return;
        }
        
        const event = events[index];
        executeEvent(event);
        
        index++;
        
        // 计算下一个事件的时间间隔
        let nextDelay = 0;
        if (index < events.length) {
            nextDelay = (events[index].timestamp - event.timestamp) / speed;
        }
        
        playbackInterval = setTimeout(executeNext, Math.max(nextDelay, 10));
    }
    
    executeNext();
}

// 执行单个事件
function executeEvent(event) {
    switch (event.type) {
        case 'mousemove':
            // 模拟鼠标移动
            console.log(`移动鼠标到: (${event.data.screenX}, ${event.data.screenY})`);
            break;
            
        case 'mousedown':
            console.log(`鼠标按下: 按钮 ${event.data.button} 在 (${event.data.screenX}, ${event.data.screenY})`);
            break;
            
        case 'mouseup':
            console.log(`鼠标释放: 按钮 ${event.data.button} 在 (${event.data.screenX}, ${event.data.screenY})`);
            break;
            
        case 'keydown':
            console.log(`键盘按下: ${event.data.key}`);
            break;
            
        case 'keyup':
            console.log(`键盘释放: ${event.data.key}`);
            break;
            
        case 'start':
        case 'stop':
            console.log(event.data.message);
            break;
    }
}

// 更新事件列表
function updateEventList() {
    if (events.length === 0) {
        eventList.innerHTML = `
            <div class="text-center text-white/60 py-8">
                <i class="fas fa-inbox text-2xl mb-2"></i>
                <p>暂无事件记录</p>
            </div>
        `;
        return;
    }
    
    const recentEvents = events.slice(-10).reverse();
    eventList.innerHTML = recentEvents.map(event => `
        <div class="event-item">
            <div class="flex justify-between items-center">
                <span class="font-mono">${event.type}</span>
                <span class="text-white/60">${event.timestamp.toFixed(1)}ms</span>
            </div>
            <div class="text-xs text-white/70 mt-1">
                ${formatEventData(event)}
            </div>
        </div>
    `).join('');
}

// 格式化事件数据
function formatEventData(event) {
    switch (event.type) {
        case 'mousemove':
        case 'mousedown':
        case 'mouseup':
            return `(${event.data.screenX}, ${event.data.screenY})`;
        case 'keydown':
        case 'keyup':
            return `${event.data.key} (${event.data.code})`;
        default:
            return JSON.stringify(event.data);
    }
}

// 更新统计信息
function updateStats() {
    eventCount.textContent = events.length;
    
    if (events.length > 0) {
        const duration = events[events.length - 1].timestamp;
        recordDuration.textContent = (duration / 1000).toFixed(1) + 's';
    } else {
        recordDuration.textContent = '0.0s';
    }
}

// 初始化
updateSpeedDisplay();
updateEventList();
updateStats();

// 监听全局快捷键
window.addEventListener('keydown', (e) => {
    if (e.ctrlKey && e.shiftKey) {
        if (e.key === 'R' || e.key === 'r') {
            e.preventDefault();
            toggleRecording();
        } else if (e.key === 'P' || e.key === 'p') {
            e.preventDefault();
            togglePlayback();
        }
    }
});
